﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VirtualPress.Portal.WebLogic.Authentication;
using VirtualPress.Infrastructure.Entities.Enum;
using VirtualPress.Portal.Biz;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Portal.Web.Areas.WorkSpace.Models;
using VirtualPress.Portal.WebLogic;
using System.IO;
using System.Linq.Expressions;
using VirtualPress.Infrastructure.Entities.Repository;
using VirtualPress.Tool.Framework;

namespace VirtualPress.Portal.Web.Areas.WorkSpace.Controllers
{
#if !DEBUG
    [ErrorHandle]
#endif
    [Auth(UserRole.JounalsAdmin, UserRole.Admin)]
    [WorkSpace(UserRole.JounalsAdmin)]
    public class ConsoleController : Controller
    {
        public ActionResult Index(int journal = -1)
        {
            Periodical data = ViewBag.Journal;
            if (data.IsNew)
            {
                return RedirectToAction("Install");
            }
            ViewBag.ArticleCount = new Article().Count(c => c.Peri_Id == data.Id && !c.IsDelete);
            ViewBag.JournalItemCount = new PeriodicalItem().Count(c => c.PeriodicalId == data.Id && c.Status == (int)JournalItemStatus.Publish);
            var container = new List<int>() { 0, 2, 4, 6, 8, 10 };
            var waitArticle = new Article().FindAll(
                c => c.Peri_Id == data.Id && container.Contains(c.Status) && !c.IsDelete,
                c => c.Id, 0, 5);
            ViewBag.WaitProccess = waitArticle;
            var counsellor = JournalBiz.GetAllLeaguer(data.Id, 0, 5);
            if (counsellor != null)
            {
                counsellor.ForEach(c => {
                    c.LoadUser(new User().Find(c.UserName), new Expert().Find(c.UserName));
                });
            }
            ViewBag.Counsellor = counsellor;
            return View();
        }
        public ActionResult Install()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult install(int journal,string Password, int DefaultExamineDay, int ManuscriptPageSize, bool isFeeForExpertExmaine,
            int PricePerPrice, int PublicationPrice, string Announcement, string Attention, string ZGFW, int PagePrice = 0)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            user.Password = VirtualPress.Tool.Framework.AesAlgorithm.Encrypt(Password);
            user.PostModify();
            var journalEntity = new Periodical().Find(journal.ToString());
            if (journalEntity == null)
            {
                return RedirectToAction("Index");
            }
            journalEntity.DefaultExamineDay = DefaultExamineDay;
            journalEntity.ManuscriptPageSize = ManuscriptPageSize;
            journalEntity.PagePrice = PagePrice;
            journalEntity.IsFeeForExpertExmaine = isFeeForExpertExmaine;
            journalEntity.PricePerPrice = PricePerPrice;
            journalEntity.PublicationPrice = PublicationPrice;
            journalEntity.CallForPaper = Announcement.NoHTMLLabel("script");
            journalEntity.Attention = Attention.NoHTMLLabel("script");
            journalEntity.ZGFW = ZGFW;
            journalEntity.IsNew = false;
            if (journalEntity.PostModify() == null)
            {
                LogHelper.Write(CommonLogger.Journal, LogLevel.Error, journal + " install 失败");
            }
            return RedirectToAction("Index");
        }
        #region 期刊管理
        public ActionResult BaseInfo(int journal=-1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult BaseInfoEdit(int Id, NewJournalModel model)
        {
            var journal = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journal != null)
            {
                var file = System.Web.HttpContext.Current.Request.Files["CoverImg"];
                if (file != null && file.ContentLength > 0)
                {
                    string basedir = "/content/journal/" + journal.Name + "/coverimage/";
                    if (!System.IO.Directory.Exists(HttpContext.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Server.MapPath(basedir));
                    }
                    var fileinfo = new FileInfo(file.FileName);
                    string filePath = basedir + journal.Name + "-converimage" + fileinfo.Extension;
                    file.SaveAs(HttpContext.Server.MapPath(filePath));
                    journal.CoverImg = filePath;
                }

                journal.Admin = model.Admin;
                journal.BSGW = model.BSGW;
                journal.BSGW_EN = model.BSGW_EN;
                journal.CallForPaper = model.CallForPaper.NoHTMLLabel("script");
                journal.CallForPaper_EN = model.CallForPaper_EN.NoHTMLLabel("script");
                journal.CBDW = model.CBDW;
                journal.CBDW_EN = model.CBDW_EN;
                journal.Editer_EN = model.Editer_EN;
                journal.Editor = model.Editor;
                journal.Email = model.Email;
                journal.FoundTime = model.FoundTime;
                journal.GJBZLXCBWH = model.GJBZLXCBWH;
                journal.GJGW = model.GJGW;
                journal.GJGW_EN = model.GJGW;
                journal.GNTYLXCBWH = model.GNTYLXCBWH;
                journal.IndType = (Infrastructure.Entities.Enum.Profession)model.IndType;
                //journale.Introduction = model.Introduction;
                //journale.Introduction_EN = model.Introduction_EN;
                journal.ISSN_Online = model.ISSN_Online;
                journal.ISSN_Print = model.ISSN_Print;
                journal.Name = model.Name;
                journal.Name_EN = model.Name_EN;
                journal.Press_Id = model.Press_Id;
                journal.PubRate = (PubRate)model.PubRate;
                journal.PubTime = model.PubTime;
                journal.Range = model.Range;
                journal.RegTime = model.RegTime;
                //journale.Retrieval = model.Retrieval;
                journal.XBDW = model.XBDW;
                journal.XBDW_EN = model.XBDW_EN;
                journal.YFDH = model.YFDH;
                journal.ZBDW = model.ZBDW;
                journal.ZBDW_EN = model.ZBDW_EN;
                journal.ZCDW = model.ZCDW;
                journal.ZCDW_EN = model.ZCDW_EN;
                journal.ZGDW = model.ZGDW;
                journal.ZGDW_EN = model.ZGDW_EN;

                if (journal.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=baseinfoedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=baseinfoedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Introduction(int journal = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult IntrodutionEdit(int Id, string Introduction,string detail, string Introduction_EN)
        {
            var journale = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journale != null)
            {
                journale.Introduction = Introduction.NoHTMLLabel("script");
                journale.Introduction_EN = Introduction_EN.NoHTMLLabel("script");
                journale.Detail = detail;
                if (journale.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=introdutionedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=introdutionedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Announcement(int journal = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AnnouncementEdit(int Id, string Announcement, string Announcement_EN="")
        {
            var journale = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journale != null)
            {
                journale.CallForPaper = Announcement.NoHTMLLabel("script");
                //journale.CallForPaper_EN = Announcement_EN;
                if (journale.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=announcementedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=announcementedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Retrieval(int journal = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult RetrievalEdit(int Id, string Retrieval)
        {
            var journale = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journale != null)
            {
                journale.Retrieval = Retrieval.NoHTMLLabel("script");
                if (journale.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=retrievaledit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=retrievaledit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Attention(int journal = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AttentionEdit(int Id, string Attention)
        {
            var journale = new Periodical().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journale != null)
            {
                journale.Attention = Attention.NoHTMLLabel("script");
                if (journale.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=attentionedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=attentionedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Links(int journal = -1,int page =0)
        {
            Periodical entity = ViewBag.Journal;
            var list = new ItemListBox<FriendLink>(JournalBiz.GetAllLinks(c => c.RelationId == entity.Id && c.RelationType==1, page, 20));
            list.BuildPage(JournalBiz.GetAllLinksForPage(c => c.RelationId == entity.Id && c.RelationType == 1),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.Links = list;
            return View();
        }
        public ActionResult AddLinks(int journal= -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddLinks(int Id, string Title, string URL, string Remark)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            FriendLink item = JournalBiz.SaveNewFriendLink(new FriendLink()
            { 
                CreateTime=DateTime.Now,
                RelationId=Id,
                RelationType=1,
                Remark=Remark,
                Title=Title,
                URL = URL
            });
            if (item != null)
            {
                return Redirect("/workSpace/console/links");
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=addlinks&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult LinkEdit(int Id,int journal = -1)
        {
            FriendLink item = JournalBiz.GetLink(Id);
            ViewBag.Link = item;
            return View();
        }
        [HttpPost]
        public ActionResult LinkEdit(int Id, string Title, string URL, string Remark)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            FriendLink data = JournalBiz.GetLink(Id);
            if (data != null)
            {
                data.Title = Title;
                data.URL = URL;
                data.Remark = Remark;
                if (data.PostModify() != null)
                {
                    return Redirect("/workSpace/console/links");
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=linkedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult LinkCancel(int Id,int journal = -1)
        {
            FriendLink link = new FriendLink().Find(Id.ToString());// JournalBiz.GetLink(Id);
            if (link != null)
            {
                link.PostDelete();
            }
            return Redirect(String.Format("/WorkSpace/Console/Links{0}", journal >= 0 ? "?journal=" + journal : ""));
        }
        public ActionResult Settings(int journal = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult Settings(string Path, int DefaultExamineDay, int ManuscriptPageSize, 
            bool isFeeForExpertExmaine, int PricePerPrice, int PublicationPrice, string ZGFW,
            int journal = -1, int PagePrice = 0)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            Periodical entity = null;
            if (journal != -1)
            {
                entity = new Periodical().Find(journal.ToString());
            }
            else
            {
                entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }

            var file = System.Web.HttpContext.Current.Request.Files["Path"];
            if (file != null && file.ContentLength > 0)
            {
                string basedir = "/content/journal/" + entity.Name + "/settings/";
                if (!System.IO.Directory.Exists(HttpContext.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Server.MapPath(basedir));
                }
                var fileinfo = new FileInfo(file.FileName);
                string filePath = basedir + entity.Name + "-templete" + fileinfo.Extension;
                file.SaveAs(HttpContext.Server.MapPath(filePath));
                entity.ManuscriptTemplete = filePath;
            }

            entity.DefaultExamineDay = DefaultExamineDay;
            entity.ManuscriptPageSize = ManuscriptPageSize;
            entity.IsFeeForExpertExmaine = isFeeForExpertExmaine;
            entity.PagePrice = PagePrice;
            entity.PricePerPrice = PricePerPrice;
            entity.ZGFW = ZGFW.Replace("\r\n","");
            entity.PublicationPrice = PublicationPrice;
            if (entity.PostModify() != null)
            {
                return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=settings&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + journal : ""));
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=settings&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + journal : ""));
        }
        public ActionResult News(int page = 0)
        {
            Periodical journal = ViewBag.Journal;
            var data = new ItemListBox<News>(CommonBiz.GetAllNews(NewsType.JournalNews,
                journal.Id, OrganizationType.Journal, page, 20));
            data.BuildPage(CommonBiz.GetAllNewsForPage(journal.Id, OrganizationType.Journal, NewsType.JournalNews),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.News = data;
            return View();
        }
        public ActionResult AddNews()
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddNews(string Title, string DisplayEditor, string Form, string Content)
        {
            Periodical journal = ViewBag.Journal;
            CommonBiz.SaveNews(new News()
            {
                Content = Content.NoHTMLLabel("script"),
                CreateDate = DateTime.Now,
                DisplayEditor = DisplayEditor,
                Editor = HttpContext.User.Identity.Name,
                Form = Form,
                Type = NewsType.JournalNews,
                Title = Title,
                OrgId = journal.Id,
                OrgType = OrganizationType.Journal
            });
            return Redirect("/WorkSpace/console/News");
        }
        public ActionResult NewsEdit(int Id)
        {
            ViewBag.Data = new News().Find(Id.ToString());
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult NewsEdit(int Id, string Title, string DisplayEditor, string Form, string Content)
        {
            var data = new News().Find(Id.ToString());
            if (data != null)
            {
                data.Title = Title;
                data.DisplayEditor = DisplayEditor;
                data.Form = Form;
                data.Content = Content.NoHTMLLabel("script");
                data.PostModify();
            }
            return Redirect("/WorkSpace/Console/News");
        }
        public ActionResult NewsCancel(int Id)
        {
            var data = new News().Find(Id.ToString());
            if (data != null)
            {
                data.PostDelete();
            }
            return Redirect("/WorkSpace/Console/News");
        }
        public ActionResult Download(int page = 0)
        {
            Periodical journal = ViewBag.Journal;
            var data = new ItemListBox<Download>(CommonBiz.GetAllDownloadFile(
                DownloadType.JournalFile, OrganizationType.Journal, journal.Id, page, 20));
            data.BuildPage(CommonBiz.GetAllDownloadFileForPage(DownloadType.JournalFile,
                 OrganizationType.Journal, journal.Id),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.News = data;
            return View();
        }
        public ActionResult AddDownloadFile()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddDownloadFile(string title, string remark)
        {
            Periodical journal = ViewBag.Journal;
            CommonBiz.SaveDownloadFile(journal.Id, OrganizationType.Journal, title, remark.Replace("\r\n", "<br/>"),
                 DownloadType.JournalFile, journal.Name, "file");
            return Redirect("/WorkSpace/console/Download");
        }
        public ActionResult DownloadFileEdit(int id)
        {
            Periodical journal = ViewBag.Journal;
            var file = new Download().Find(id.ToString());
            if (file == null || file.OrgId != journal.Id)
            {
                return Redirect("/WorkSpace/console/Download");
            }
            ViewBag.DownloadFile = file;
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult DownloadFileEdit(int id, string title, string remark)
        {
            Periodical journal = ViewBag.Journal;
            CommonBiz.EditDownloadFile(id, title, remark.Replace("\r\n", "<br/>"), journal.Name, "file");
            return Redirect("/WorkSpace/console/Download");
        }
        public ActionResult DownloadFileCancel(int id)
        {
            CommonBiz.DeleteDownloadFile(id);
            return Redirect("/WorkSpace/console/Download");
        }
        #endregion

        #region 人员管理
        /*编委会部分*********************/
        /// <summary>
        /// 编委会
        /// </summary>
        /// <param name="journal"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Counsellor(int journal = -1, int page = 0)
        {
            Periodical entity = ViewBag.Journal;
            var editorial = JournalBiz.GetAllLeaguer(entity.Id, page, 20);
            ItemListBox<Organization> list = new ItemListBox<Organization>(editorial);
            list.BuildPage(JournalBiz.GetAllLeaguerForPage(entity.Id),page,20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });

            ViewBag.Editorial = list;
            return View();
        }
        /// <summary>
        /// 添加编委会
        /// </summary>
        /// <param name="journal"></param>
        /// <returns></returns>
        public ActionResult InviteCounsellor(int journal = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult InviteCounsellor(string ExpertAccount, int journal = -1)
        {
            Periodical journalEntity = ViewBag.Journal;
            if (new Organization().Any(c => c.OrgId == journalEntity.Id && c.OrgType == (int)OrganizationType.Journal && c.Status == (int)JournalStatus.Counsellor
                && c.ApplyStatus == 1 && c.UserName == ExpertAccount))
            {
                //如果已经存在
                ViewBag.Exist = true;
                ViewBag.Account = ExpertAccount;
                ViewBag.Expert = null;
                return View(); 
            }
            User user = new User().Find(ExpertAccount);
            ViewBag.Account = ExpertAccount;
            ViewBag.Expert = user;
            ViewBag.Exist = false;
            return View();
        }
        /// <summary>
        /// 邀请站内专家加入编委会
        /// </summary>
        /// <param name="ExpertAccount"></param>
        /// <param name="journal"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DoInvite(string ExpertAccount, int journal = -1)
        {
            Periodical entity = null;
            if (journal != -1)
            {
                entity = new Periodical().Find(journal.ToString());
            }
            else
            {
                entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }

            if (JournalBiz.DoInviteForExpert(ExpertAccount, entity.Id))
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=doinvite&s=1");
            }
            else
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=doinvite&s=0");
            }
        }
        public ActionResult MailToInvite(string u="", int journal = -1,int i=0)
        {
            ViewBag.Account = u;
            return View();
        }
        /// <summary>
        /// 邀请站外专家加入编委会
        /// </summary>
        /// <param name="ExpertAccount"></param>
        /// <param name="journal"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MailToInvite(string ExpertAccount, int journal = -1)
        {
            Periodical entity = null;
            if (journal != -1)
            {
                entity = new Periodical().Find(journal.ToString());
            }
            else
            {
                entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }

            int result = JournalBiz.MailToInviteForExpert(ExpertAccount, entity.Id);
            if (result == 1)
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=mailtoinvite&s=1");
            }
            else if (result == 2)
            {
                ViewBag.Message = "该专家账号已在平台注册存在，您可以通过从现有专家库添加来邀请他（她）加入编委会";
            }
            else
            {
                ViewBag.Message = "该账号已在平台注册存在，但并不是专家账号。如有疑问请联系管理员协助解决";
            }
            return View();
        }
        /// <summary>
        /// 移除管委会成员
        /// </summary>
        /// <param name="u"></param>
        /// <param name="journal"></param>
        /// <returns></returns>
        public ActionResult CacnelEditorial(string u,int journal = -1)
        {
            Periodical entity = ViewBag.Journal;
            JournalBiz.CancelEditorial(entity.Id, u);
            return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=cacneleditorial&s=1&journal=" + journal);
        }
        
        /*校对员部分**********************/
        //public ActionResult Reviser(int journal = -1, int page = 0)
        //{
        //    Periodical entity = ViewBag.Journal;
        //    var editorial = JournalBiz.GetAllReviser(entity.Id, page, 20);
        //    ItemListBox<Organization> list = new ItemListBox<Organization>(editorial);
        //    list.BuildPage(JournalBiz.GetAllLeaguerForPage(entity.Id), page, 20,
        //         new PageParameter()
        //         {
        //             IsActive = false,
        //             Param_page = "page",
        //             Style = "workspace"
        //         });

        //    ViewBag.Editorial = list;
        //    return View();
        //}
        //public ActionResult InviteReviser(int journal = -1)
        //{
        //    return View();
        //}
        //[HttpPost]
        //public ActionResult InviteReviser(string UserAccount, int journal = -1)
        //{
        //    User user = new User().Find(UserAccount);
        //    ViewBag.Account = UserAccount;
        //    //ViewBag.User = user;
        //    return View();
        //}
        ///// <summary>
        ///// 邀请站内会员加入初审员
        ///// </summary>
        ///// <param name="ExpertAccount"></param>
        ///// <param name="journal"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult DoReviserInvite(string UserAccount, int journal = -1)
        //{
        //    Periodical entity = null;
        //    if (journal != -1)
        //    {
        //        entity = new Periodical().Find(journal.ToString());
        //    }
        //    else
        //    {
        //        entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
        //    }

        //    if (JournalBiz.DoInviteForRevoser(UserAccount, entity.Id))
        //    {
        //        return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=doreviserinvite&s=1");
        //    }
        //    else
        //    {
        //        return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=doreviserinvite&s=0");
        //    }
        //}
        //public ActionResult MailToInviteReviser(int journal = -1)
        //{
        //    return View();
        //}
        //[HttpPost]
        //public ActionResult MailToInviteReviser(string ExpertAccount, int journal = -1)
        //{
        //    Periodical entity = null;
        //    if (journal != -1)
        //    {
        //        entity = new Periodical().Find(journal.ToString());
        //    }
        //    else
        //    {
        //        entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
        //    }

        //    if (JournalBiz.MailToInviteForReviser(ExpertAccount, entity.Id))
        //    {
        //        return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=mailtoinvitereviser&s=1");
        //    }
        //    ViewBag.Message = "该会员账号已在平台注册存在，您可以通过从现有会员中添加来邀请他（她）加入初审工作";
        //    return View();
        //}
        ///// <summary>
        ///// 移除管委会成员
        ///// </summary>
        ///// <param name="u"></param>
        ///// <param name="journal"></param>
        ///// <returns></returns>
        //public ActionResult CacnelReviser(string u, int journal = -1)
        //{
        //    Periodical entity = ViewBag.Journal;
        //    JournalBiz.CancelResiver(entity.Id, u);
        //    return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=cacnelreviser&s=1&journal=" + journal);
        //}
        
        /*待确认部分**********************/
        public ActionResult InvitePending(int journal = -1, int page = 0)
        {
            Periodical entity = ViewBag.Journal;
            var editorial = JournalBiz.GetAllPendingMember(entity.Id, page, 20);
            ItemListBox<Organization> list = new ItemListBox<Organization>(editorial);
            list.BuildPage(JournalBiz.GetAllLeaguerForPage(entity.Id), page, 20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });

            ViewBag.Editorial = list;
            return View();
        }

        //public void ReMailToInviteExpert(string u, int journal = -1)
        //{
        //    Periodical data = ViewBag.Journal;
        //    JournalBiz.ReMailToInviteExpert(u, data.Id);
        //}
        #endregion

        #region 征稿中心
        /// <summary>
        /// 
        /// </summary>
        /// <param name="journal"></param>
        /// <param name="group">
        /// 0：最新稿件 （type= 0）
        /// 1：待分配稿件（type= 专审待分配:2; 专审完成:4; 专审修订完成:6; 终审完成:8; 终审修订完成:10）
        /// 2：专审稿件(type= 专审中:3; 专审修订:5)
        /// 3：终审稿件(type= 终审中:7; 终审修订:9)
        /// 4：录用稿件(type= 录用已缴费:30; 已出版:40)
        /// 5：拒绝稿件(type= 废弃:99)
        /// 6：待缴费稿件(type= 专审待缴费:1; 录用:20; 补交费:80)
        /// 9：全部稿件
        /// </param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Article(int journal = -1,int group = 0, int page = 0)
        {
            var groupmap = new
            {
                最新 = new List<int>() { 0 },
                待分配 = new List<int>() { 2, 4, 6, 8, 10 },
                专审 = new List<int>() { 3, 5 },
                终审 = new List<int>() { 7, 9 },
                录用 = new List<int>() { 30, 40 },
                拒绝 = new List<int>() { 99 },
                缴费 = new List<int>() { 1, 20, 80 }
            };
            Periodical entity = ViewBag.Journal;
            Expression<Func<T_Article, bool>> where = null;
            if (group == 9)
            {
                where = c => c.Peri_Id == entity.Id && !c.IsDelete;
            }
            else
            {
                List<int> contain = new List<int>();
                switch (group)
                {
                    default:
                    case 0:
                        contain = groupmap.最新;
                        break;
                    case 1:
                        contain = groupmap.待分配;
                        break;
                    case 2:
                        contain = groupmap.专审;
                        break;
                    case 3:
                        contain = groupmap.终审;
                        break;
                    case 4:
                        contain = groupmap.录用;
                        break;
                    case 5:
                        contain = groupmap.拒绝;
                        break;
                    case 6:
                        contain = groupmap.缴费;
                        break;
                }  
                where = c => c.Peri_Id == entity.Id && contain.Contains(c.Status) && !c.IsDelete;
            }
            List<Article> list = JournalBiz.GetAllArticle(where,group == 2, page, 20);
            foreach (var article in list)
            {
                if (article.Status == ArticleStatus.ZhuanShenDaiJiaoFei ||
                    article.Status == ArticleStatus.LuYong)
                {
                    var reckoning = new Reckoning().Find(c =>
                        c.PayFor == 0 && c.RaletionId == article.Id && c.Status == 0);
                    if (reckoning != null)
                    {
                        article.WaitPay = reckoning.TotalPay;
                    }
                }
            }
            var data = new ItemListBox<Article>(list).BuildPage(
                JournalBiz.GetAllArticleForPage(where),
                page, 20,
                new PageParameter()
                {
                    IsActive = false,
                    Param_page = "page",
                    Style = "workspace"
                });
            ViewBag.Article = data;
            ViewBag.Group = group;
            ViewBag.Journal = entity;
            return View();
        }
        [SelfArticle("id")]
        public ActionResult ArticleDetail(int id)
        {
            var article = new Article().Find(c => c.Id == id);
            var author = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            //作者信息
            ViewBag.ArticleAuthor = author;
            //稿件
            ViewBag.Article = article;
            //期刊
            ViewBag.Journal = journal;
            //附件
            ViewBag.Attachment = new Appendix().FindAll(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);           
            //稿件历史
            ViewBag.History = JournalBiz.GetAllArticleHistory(article.Id);
            //审稿记录
            var records = JournalBiz.GetAllAuditingRecord(article.Id);;
            ViewBag.AuditingRecord = records;
            var ExpertList = JournalBiz.FindExpertForExamine(journal, article,
                records.Where(c=>c.Step != ExamineStep.ChuShen)
                       .Select(c => c.UserName).ToList());
            ViewBag.ExpertList = ExpertList;
            return View();
        }
        public ActionResult ShowSuggestion(int id)
        {
            Appendix attachment = new Appendix().Find(id.ToString());
            if(attachment.AttachmentType != AttachmentType.Manuscript)
            {
                return Redirect("/workspace/console/index");
            }
            Article article = new Article().Find(attachment.RaletionId.ToString());
            if (article == null)
            {
                return Redirect("/workspace/console/index");
            }
            Periodical journal = new Periodical().Find(article.Peri_Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (journal == null || user == null || 
                !(journal.Admin.ToLower() == HttpContext.User.Identity.Name.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return Redirect("/workspace/console/index");
            }
            ViewBag.Attachment = attachment;
            return View();
        }
        public ActionResult CancelArticle(int id, int group = 0)
        {
            JournalBiz.CancelArticleForJournal(id);
            return RedirectToAction("Article", new { group = group });
        }
        public ActionResult ConfirmIsPay(int id)
        {
            var article = new Article().Find(id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (article != null && user != null)
            {
                var journal = new Periodical().Find(article.Peri_Id.ToString());
                if (journal != null)
                {
                    if (journal.Admin.ToLower() == HttpContext.User.Identity.Name.ToLower() ||
                        user.SystemRole == UserRole.Admin)
                    {
                        var articleHistory = new ArticleHistory() { 
                            CreateTime=DateTime.Now,
                            PreStatus = article.Status,
                            ManuscriptId = article.Id,
                            Message="管理员确认缴费",
                            Operator=HttpContext.User.Identity.Name
                        };

                        if(article.Status == ArticleStatus.ZhuanShenDaiJiaoFei)
                        {
                            article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                            article.PostModify();

                            articleHistory.CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei;
                        }
                        else if(article.Status == ArticleStatus.LuYong)
                        {
                            article.Status = ArticleStatus.ChuBanYiJiaoFei;
                            article.PostModify();

                            articleHistory.CurrentStatus = ArticleStatus.ChuBanYiJiaoFei;
                        }
                        else if (article.Status == ArticleStatus.BuJiaoFei)
                        {
                            article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                            article.PostModify();

                            articleHistory.CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei;
                        }
                        articleHistory.PostAdd();

                        var bill = new Reckoning().Find(c => c.PayFor == 0 && c.RaletionId == article.Id && c.Status == 0);
                        if (bill != null)
                        {
                            bill.Status = BillStatus.ZhiFuWanCheng;
                            bill.PayType = PayType.Offline;
                            bill.PostModify();
                        }
                    }
                }
            }
            return RedirectToAction("Article", new { group = 6 });
        }
        public ActionResult NewManuscriptCheck(int id,int journal=-1)
        {
            Periodical entity = ViewBag.Journal;
            var article = new Article().Find(id.ToString());
            if (article.Peri_Id != entity.Id)
            {
                return Redirect(String.Format("/workspace/console/index{0}", journal >= 0 ? "?journal=" + journal : ""));
            }
            ViewBag.Article = article;
            var articleAuthor = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            ViewBag.Authors = articleAuthor;
            ViewBag.Attachment = new Appendix().FindAll(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewManuscriptCheck(int id, bool optionsRadios, string RefuseMessage, int Page = 0, int journal = -1)
        {
            Periodical entity = null;
            if (journal != -1)
            {
                entity = new Periodical().Find(journal.ToString());
            }
            else
            {
                entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }
            if (entity == null)
            {
                return Redirect(String.Format("/workspace/console/index{0}", journal >= 0 ? "?journal=" + journal : ""));
            }
            Article article = new Article().Find(id.ToString());
            if (article == null)
            {
                return Redirect(String.Format("/workspace/console/index{0}", journal >= 0 ? "?journal=" + journal : ""));
            }
            if (JournalBiz.DoManuscriptCheck(article, Page, optionsRadios, RefuseMessage.NoHTMLLabel("script")))
            {
                return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=console&a=newmanuscriptcheck&s={0}{1}",optionsRadios?"1":"0", "&journal=" + journal));
            }
            return Redirect("/workspace/console/article?group=0");
            
        }
        /// <summary>
        /// 专审分配
        /// </summary>
        /// <param name="id"></param>
        /// <param name="journal"></param>
        /// <returns></returns>
        public ActionResult Distribution(int id, int journal = -1)
        {
            Periodical entity = ViewBag.Journal;
            var article = new Article().Find(id.ToString());
            if (article == null)
            {
                return Redirect(String.Format("/workspace/home/index{0}", journal >= 0 ? "?journal=" + journal : ""));
            }
            var ExpertList = JournalBiz.FindExpertForExamine(entity, article, null);
            ViewBag.Article = article;
            ViewBag.ExpertList = ExpertList;
            var authors = new ArticleAuthor().FindAll(
                c => c.ManuscriptId == article.Id);
            ViewBag.Author = authors;
            var attachment = new Appendix().FindAll(
                c => c.Type == 1 && c.RaletionId == article.Id);
            ViewBag.Attachment = attachment;
            return View();
        }
        [HttpPost]
        public ActionResult Distribution(int articleId, int finishDate, string experts)
        {
            JournalBiz.DoDistribution(articleId,DateTime.Now.AddDays(finishDate), experts);
            return RedirectToAction("article", new { group = 1 });
        }
        public ActionResult CancelExamine(int id,int articleId)
        {
            JournalBiz.CancelExamineForArticle(id);
            return RedirectToAction("articledetail", new { id = articleId });
        }
        public void AppendExamineExpert(int articleId, string expert, int finishDate)
        {
            JournalBiz.AppendExamineExpert(articleId, expert, DateTime.Now.AddDays(finishDate));
        }
        public void UrgeExamine(int id) 
        {
            JournalBiz.urgeExamine(id);
        }
        ///// <summary>
        ///// 专审结束设置
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult Examinefinish(int articleId, int result, string msg)
        //{
        //    bool success = JournalBiz.FinishExamine(articleId, result, msg.NoHTMLLabel("script"));
        //    if (!success)
        //    {
        //        return Redirect("/workspace/console/articledetail/" + articleId);
        //    }
        //    return Redirect("/workspace/console/article?group=1");
        //}
        public ActionResult CheckAndAcceptance(int articleId)
        {
            ViewBag.Article = new Article().Find(articleId.ToString());
            ViewBag.Authors = new ArticleAuthor().FindAll(c => c.ManuscriptId == articleId);
            ViewBag.Records = JournalBiz.GetAllAuditingRecord(articleId, c => c.ExamineStatus == (int)ExamineStatus.WanCheng &&
                c.ManuscriptId == articleId && c.Step == (int)ExamineStep.ZhuanShen);
            return View();
        }
        public ActionResult Examineresult(int id,int journal = -1)
        {
            AuditingRecord record = new AuditingRecord().Find(id.ToString());
            Periodical entity = ViewBag.Journal;
            Article article = new Article().Find(record.ManuscriptId.ToString());
            ViewBag.Authors = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            ViewBag.Record = record;
            ViewBag.Article = article;

            if (record.AppendixId > 0)
            {
                ViewBag.Attachment = new Appendix().Find(record.AppendixId.ToString());
            }
            return View();
        }
        /// <summary>
        /// 专审完成，验收
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public ActionResult acceptanceexamine(int articleId, int result, string msg, string sheetids)
        {
            Periodical journal = ViewBag.Journal;
            int[] recordsId = null;
            if (!String.IsNullOrEmpty(sheetids))
            {
                recordsId = sheetids.Split(';').Where(c => !String.IsNullOrEmpty(c)).Select(c => Int32.Parse(c)).ToArray();
            }
            int res = JournalBiz.AcceptanceExamine(articleId, result, msg.NoHTMLLabel("script"), recordsId);
            if (res == 2)
            {
                var article = new Article().Find(articleId.ToString());
                return RedirectToAction("distribution", new { id = articleId, journal = journal.Id });
            }
            return Redirect("/workspace/console/article?group=1");
        }
        public ActionResult conclusiveexamine(int articleId,int totalPay, int result, string msg)
        {
            bool success = JournalBiz.ConclusiveExamine(articleId, totalPay, result, msg.NoHTMLLabel("script"));
            return Redirect("/workspace/console/article?group=3");
        }
        /// <summary>
        /// 手工添加稿件
        /// </summary>
        /// <returns></returns>
        public ActionResult manualArticle()
        {
            var entity = ViewBag.Journal;
            var author = new Author().FindAll(c => c.UserName == HttpContext.User.Identity.Name);
            ViewBag.Author = author;
            return View();
        }
        [HttpPost]
        public ActionResult manualArticle(ContributeModel model)
        {
            if (!JournalBiz.ManualArticle(new Article()
            {
                ArticleType= Infrastructure.Entities.Enum.ArticleType.Journal,
                Abstract = model.Abstract.Replace("\r\n", "<br/>"),
                Abstract_EN = model.Abstract_EN.Replace("\r\n", "<br/>"),
                CreateTime = DateTime.Now,
                KeyWords = model.KeyWords,
                KeyWords_EN = model.KeyWords_EN,
                Peri_Id = model.journalId,
                Status = ArticleStatus.DaiChuBan,
                Title = model.Title,
                Title_EN = model.Title_EN,
                UserName = HttpContext.User.Identity.Name,
                SubmitTime = DateTime.Now,
                IsDelete = false,
                GJFW = String.IsNullOrEmpty(model.GJFW) ? "" : (model.GJFW.EndsWith(";") ? model.GJFW.Remove(model.GJFW.Length - 1) : model.GJFW)
            }, model.Author.Split(';').ToList()))
            {
                RedirectToAction("articlebank");
            }

            //发送审核邮件
            return RedirectToAction("articlebank");
        }
        public ActionResult author(int page=0)
        {
            var authors = UserBiz.GetAllAuthor(HttpContext.User.Identity.Name, page, 20);
            ViewBag.Author = new ItemListBox<Author>(authors)
                .BuildPage(UserBiz.GetAllAuthorForPage(HttpContext.User.Identity.Name),
                page, 20,
                new PageParameter() { 
                    Style="workspace"
                });
            return View();
        }
        public ActionResult CancelAuthor(int id)
        {
            var author = new Author().Find(c => c.Id == id && c.UserName == HttpContext.User.Identity.Name);
            if (author != null)
            {
                author.PostDelete();
            }
            return RedirectToAction("Author");
        }
        public ActionResult authorinfo()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult authorinfo(NewAuthorModel model)
        {
            UserBiz.SaveNewAuthor(new Author()
            {
                Address = model.Address,
                CreateTime = DateTime.Now,
                Degree = model.Degree,
                Department = model.Department,
                Department_EN = model.Department_EN,
                Email = model.Email,
                FirstName = model.FirstName,
                Gender = (Gender)model.Gender,
                Introduction = model.Introduction,
                Introduction_EN = model.Introduction_EN,
                LastName = model.LastName,
                PostCode = model.PostCode,
                Title = model.Title,
                Title_EN = model.Title_EN,
                UserName = HttpContext.User.Identity.Name,
                Phone = model.Phone
            });
            return RedirectToAction("Author");
        }
        [HttpPost]
        public ActionResult OverExamie(int articleId)
        {
            JournalBiz.OverExamie(articleId, "Article");
            return RedirectToAction("ArticleBank");
        }
        #endregion

        #region 稿件出版
        public ActionResult ArticleBank(int publish = -1, int journal = -1, int page = 0)
        {
            Periodical entity = ViewBag.Journal;
            if (publish > 0)
            {
                var journalItem = new PeriodicalItem().Find(publish.ToString());
                ViewBag.JournalItem = journalItem;
            }
            Expression<Func<T_Article, bool>> where = c => c.Peri_Id == entity.Id && c.Status == (int)ArticleStatus.DaiChuBan && !c.IsDelete;
            List<Article> list = JournalBiz.GetAllArticle(where, page, 20);
            var data = new ItemListBox<Article>(list).BuildPage(
                JournalBiz.GetAllArticleForPage(where),
                page, 20,
                new PageParameter()
                {
                    IsActive = false,
                    Param_page = "page",
                    Style = "workspace"
                });
            ViewBag.Article = data;
            ViewBag.Journal = entity;
            return View();
        }
        public ActionResult Publish(int page =0,int journal=-1)
        {
            Periodical entity = ViewBag.Journal;
            List<PeriodicalItem> data = JournalBiz.GetAllJournalItem(entity.Id, page, 10);
            ViewBag.Data = new ItemListBox<PeriodicalItem>(data)
                .BuildPage(JournalBiz.GetAllJournalItemForPage(entity.Id), page, 10,
                    new PageParameter() { Style = "workspace" });
            return View();
        }
        public ActionResult NewPublish()
        {
            return View();
        }
        [HttpPost]
        public ActionResult NewPublish(string Manuscriptcode, string PublishDate,int journal=-1)
        {
            Periodical entity = null;
            if (journal != -1)
            {
                entity = new Periodical().Find(journal.ToString());
            }
            else
            {
                entity = new Periodical().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }
            if (entity == null)
            {
                return Redirect(String.Format("/workspace/home/index{0}", journal >= 0 ? "?journal=" + journal : ""));
            }
            JournalBiz.NewJournalItem(entity.Id, Manuscriptcode, PublishDate);
            return RedirectToAction("Publish");
        }
        public ActionResult DeleteJournalItem(int journalItemId,int journal = -1)
        {
            Periodical entity = ViewBag.Journal;
            JournalBiz.DeleteJournalItem(entity.Id, journalItemId);
            return RedirectToAction("Publish");
        }
        public ActionResult PublishJournalItem(int journalItemId)
        {
            int success = JournalBiz.PublishJournalItem(journalItemId);
            if (success==2)
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=console&a=publishjournalitem&s=2");
                //因为期刊被禁用
            }
            return RedirectToAction("Publish");
        }
        public ActionResult addArticleToPublish(int articleId, int journalItemId)
        {
            JournalBiz.AddArticleToPublish(articleId, journalItemId);
            return RedirectToAction("ArticleBank", new { publish = journalItemId });
        }
        public ActionResult PublishHistory(int page = 0, int journal = -1)
        {
            Periodical entity = ViewBag.Journal;
            List<PeriodicalItem> data = JournalBiz.GetAllPublishedJournalItem(entity.Id, page, 10);
            ViewBag.Data = new ItemListBox<PeriodicalItem>(data)
                .BuildPage(JournalBiz.GetAllPublishedJournalItemForPage(entity.Id), page, 10,
                    new PageParameter() { Style = "workspace" });
            return View();
        }
        #endregion
    }
}
